package com.itheima.mobilesafe69.engine;

import java.util.ArrayList;
import java.util.List;

import com.itheima.mobilesafe69.db.domain.AppInfo;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;

/**
 * @author qbc
 * 获取安装在手机中的应用相关信息
 */
public class AppInfoProvider {
	//
	/**
	 * @param ctx	上下文环境
	 * @return	获取每一个应用信息方法,返回List<AppInfo>集合
	 */
	public static List<AppInfo> getAppInfoList(Context ctx){
		List<AppInfo> appInfoList = new ArrayList<AppInfo>();
		//1,获取包的管理者对象
		PackageManager pm = ctx.getPackageManager();
		//2,在当前手机中已经安装上的应用
		List<PackageInfo> installedPackages = pm.getInstalledPackages(0);
		//3,循环遍历
		for (PackageInfo packageInfo : installedPackages) {
			AppInfo appInfo = new AppInfo();
			//4,循环遍历每一个应用相关信息所在对象
			//5,获取应用包名
			String packageName = packageInfo.packageName;
			appInfo.packageName = packageName;
			
			//6,获取应用名称(包相关信息---->应用Application中的相关信息------->lable节点内容(名称))
			
			String name = packageInfo.applicationInfo.loadLabel(pm).toString()+packageInfo.applicationInfo.uid;
			appInfo.name = name;
			
			//7,获取应用的图标
			Drawable icon = packageInfo.applicationInfo.loadIcon(pm);
			appInfo.drawable = icon;
			
			//8,判断当前应用是否为系统应用
			ApplicationInfo applicationInfo = packageInfo.applicationInfo;
			
			if((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == ApplicationInfo.FLAG_SYSTEM){
				//系统应用(状态机)
				appInfo.isSystem  = true;
			}else{
				//用户应用
				appInfo.isSystem  = false;
			}
			//9,判断当前应用是否为sd卡中存储的应用
			if((applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) == ApplicationInfo.FLAG_EXTERNAL_STORAGE){
				//存储在sd卡中的应用
				appInfo.isSdApp = true;
			}else{
				//存储在手机内存中的应用
				appInfo.isSdApp = false;
			}
			appInfoList.add(appInfo);
		}
		
		return appInfoList;
	}
}
